/**
 * 获取推流的stats
 * @param {*} publication
 * @param {*} milliseconds 执行或调用 code/function 需要等待的时间，以毫秒计。默认为 3000
 * @param {*} onSuccess
 * @param {*} onFailure
 */
export function publicationGetStats(publication, milliseconds = 3000, onSuccess, onFailure) {
	let intervalId = 0;
	if (!publication.hasOwnProperty('getStats')) {
		//publication is valid
		onFailure('publication is valid');
		return -1;
	}
	if (isSafariBrowserOrIphoneDevice()) {
		intervalId = setInterval(() => {
			publication
				.getStats()
				.then(stats => {
					//  console.log(`${new Date()},stats,${stats}}`);
					onSuccess(safariWebRtcPublicationStats(stats));
				})
				.catch(error => {
					onFailure(error);
				});
		}, milliseconds);
	} else {
		intervalId = setInterval(() => {
			publication
				.getStats()
				.then(stats => {
					//   console.log(`${new Date()},stats,${stats}}`);
					onSuccess(chromeWebRtcPublicationStats(stats));
				})
				.catch(error => {
					onFailure(error);
				});
		}, milliseconds);
	}
	return intervalId;
}

export function chromeWebRtcPublicationStats(data) {
	let stats = {
		actualBitrate: 0, //实际码率
		actualWidth: 0, //实际视频width
		actualHeight: 0, //实际视频height
		packetsLost: 0, //丢包数
		packetsSent: 0, //发送包数
		rate: 0, //帧率
		bytesSent: 0 //发送的字节数
	};
	for (var value of data) {
		//  console.log(value);
		let key = value[0];
		if (key === 'bweforvideo') {
			stats.actualBitrate = value[1].googActualEncBitrate ? value[1].googActualEncBitrate / 1000 : 0;
		}
		if (key.indexOf('ssrc') != -1 && key.indexOf('send') != -1) {
			if (value[1].mediaType && value[1].mediaType === 'video') {
				stats.actualWidth = value[1].googFrameWidthSent ? value[1].googFrameWidthSent : 0;
				stats.actualHeight = value[1].googFrameHeightSent ? value[1].googFrameHeightSent : 0;
				stats.rate = value[1].googFrameRateSent ? value[1].googFrameRateSent : 0;
				stats.bytesSent = value[1].bytesSent ? value[1].bytesSent : 0;
				stats.packetsSent = value[1].packetsSent ? value[1].packetsSent : 0;
				stats.packetsLost = value[1].packetsLost ? value[1].packetsLost : 0;
			}
		}
	}
	return stats;
}

export function safariWebRtcPublicationStats(data) {
	let stats = {
		actualBitrate: 0, //实际码率
		actualWidth: 0, //实际视频width
		actualHeight: 0, //实际视频height
		packetsLost: 0, //丢包数
		packetsSent: 0, //发送包数
		rate: 0, //帧率
		bytesSent: 0 //发送的字节数
	};
	data.forEach(object => {
		let keyId = object.id;
		//   console.log(`safariWebRtcPublicationStats,${new Date()},${object}}`);
		//   console.log(object);
		if (keyId.indexOf('RTCOutboundRTPVideoStream') != -1) {
			stats.bytesSent = object.bytesSent ? object.bytesSent : 0;
			stats.packetsSent = object.packetsSent ? object.packetsSent : 0;
			stats.packetsLost = object.nackCount ? object.nackCount : 0;
		}
		if (keyId.indexOf('RTCIceCandidatePair') != -1) {
			//stats.actualBitrate = object.availableOutgoingBitrate?object.availableOutgoingBitrate/1000:0;
		}
		if (keyId.indexOf('RTCMediaStreamTrack_sender') != -1) {
			if (object.frameWidth) {
				stats.actualWidth = object.frameWidth;
			}
			if (object.frameHeight) {
				stats.actualHeight = object.frameHeight;
			}
		}
	});
	return stats;
}

/**
 * 获取订阅流的stats
 * @param {*} subscription
 * @param {*} milliseconds
 * @param {*} onSuccess
 * @param {*} onFailure
 */
export function subscriptionGetStats(subscription, milliseconds = 3000, onSuccess, onFailure) {
	let intervalId = 0;
	console.log(subscription.getStats().then(res => console.log(res)));
	if (!subscription.hasOwnProperty('getStats')) {
		//publication is valid
		onFailure('subscription is valid');
		return -1;
	}
	if (isSafariBrowserOrIphoneDevice()) {
		intervalId = setInterval(() => {
			subscription
				.getStats()
				.then(stats => {
					console.log(`${new Date()},stats,${stats}}`);
					onSuccess(safariWebRtcSubscriptionStats(stats));
				})
				.catch(error => {
					onFailure(error);
				});
		}, milliseconds);
	} else {
		intervalId = setInterval(() => {
			subscription
				.getStats()
				.then(stats => {
					// console.log(`${new Date()},stats,${stats}}`);
					onSuccess(chromeWebRtcSubscriptionStats(stats));
				})
				.catch(error => {
					onFailure(error);
				});
		}, milliseconds);
	}
	return intervalId;
}

export function chromeWebRtcSubscriptionStats(data) {
	let stats = {
		actualWidth: 0, //实际视频width
		actualHeight: 0, //实际视频height
		packetsLost: 0, //丢包数
		packetsReceived: 0, //接受包数
		rate: 0, //帧率
		bytesReceived: 0, //接受的字节数(2次结果可用于计算下行视频带宽)
		delayMs: 0, //延迟毫秒数
		jitterBufferMs: 0, //抖动
		framesEncoded: 0 //累计解码的帧数
	};
	for (var value of data) {
		//   console.log(value);
		let key = value[0];
		if (key.indexOf('ssrc') != -1 && key.indexOf('recv') != -1) {
			if (value[1].mediaType && value[1].mediaType === 'video') {
				stats.actualWidth = value[1].googFrameWidthReceived ? value[1].googFrameWidthReceived : 0;
				stats.actualHeight = value[1].googFrameHeightReceived ? value[1].googFrameHeightReceived : 0;
				stats.rate = value[1].googFrameRateReceived ? value[1].googFrameRateReceived : 0;
				stats.bytesReceived = value[1].bytesReceived ? value[1].bytesReceived : 0;
				stats.packetsReceived = value[1].packetsReceived ? value[1].packetsReceived : 0;
				stats.packetsLost = value[1].packetsLost ? value[1].packetsLost : 0;
				stats.jitterBufferMs = value[1].googJitterBufferMs ? value[1].googJitterBufferMs : 0;
				stats.framesEncoded = value[1].framesDecoded ? value[1].framesDecoded : 0;
			}
		}
	}
	return stats;
}

export function safariWebRtcSubscriptionStats(data) {
	let stats = {
		actualWidth: 0, //实际视频width
		actualHeight: 0, //实际视频height
		packetsLost: 0, //丢包数
		packetsReceived: 0, //接受包数
		bytesReceived: 0, //接受的字节数(2次结果可用于计算下行视频带宽)
		framesEncoded: 0 //累计解码的帧数
	};
	data.forEach(object => {
		let keyId = object.id;
		if (keyId.indexOf('RTCInboundRTPVideoStream') != -1) {
			stats.bytesReceived = object.bytesReceived ? object.bytesReceived : 0;
			stats.packetsReceived = object.packetsReceived ? object.packetsReceived : 0;
			stats.packetsLost = object.packetsLost ? object.packetsLost : 0;
			stats.delayMs = object.totalInterFrameDelay ? object.totalInterFrameDelay : 0;
			stats.framesEncoded = object.framesDecoded ? object.framesDecoded : 0;
		}
		if (keyId.indexOf('RTCIceCandidatePair') != -1) {
			stats.actualBitrate = object.availableOutgoingBitrate ? object.availableOutgoingBitrate / 1000 : 0;
		}
		if (keyId.indexOf('RTCMediaStreamTrack_receiver') != -1) {
			if (object.frameWidth) {
				stats.actualWidth = object.frameWidth;
			}
			if (object.frameHeight) {
				stats.actualHeight = object.frameHeight;
			}
		}
	});
	return stats;
}

export function isSafariBrowserOrIphoneDevice() {
	let ipad = window.navigator.userAgent.toLowerCase().match(/ipad/);
	let iphone = window.navigator.userAgent.toLowerCase().match(/iphone/i);
	iphone = iphone !== null ? iphone[0] : null;
	ipad = ipad !== null ? ipad[0] : null;
	if (iphone === 'iphone' || ipad === 'ipad') {
		return true;
	}
	return /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent);
}

function test() {
	let a = [123, 333];
	for (const key in a) {
		console.log(key);
	}
	console.log('cccc');
	console.log(a);
	return a;
}
